package com.jaws.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 鉴权过滤器
 *
 * @author liangqm
 * @date 2018/3/2 10:52
 * @since v1.0.0
 */
@Component
public class AuthFilter extends ZuulFilter {

	private static Logger log = LoggerFactory.getLogger(AuthFilter.class);

	@Override
	public String filterType() {
		// pre：路由之前
		// routing：路由之时
		// post： 路由之后
		// error：发送错误调用
		return "pre";
	}

	@Override
	public int filterOrder() {
		// 优先级为0，数字越大，优先级越低
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		// 是否执行该过滤器，此处为true，说明需要过滤
		return true;
	}

	@Override
	public Object run() {
		// run：过滤器的具体逻辑。可用很复杂，包括查sql，nosql去判断该请求到底有没有权限访问。

		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
		Object accessToken = request.getParameter("token");

		if (accessToken == null) {
			log.warn("token is empty");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			try {
				ctx.getResponse().getWriter().write("token is empty");
			} catch (Exception e) {
			}

			return null;
		}

		log.info("ok");
		return null;
	}
}